<?php 

class Model_JobService extends Model {

    protected $_table_name = 'cmr_job_service';
    protected $_primary_key = 'id';
 
    protected function where_clause($where) {
        $where_clause = '';
        if (is_array($where)) {
            $wheres = array();
            foreach($where as $column => $value) {
                if (in_array(strtoupper($column), array('GROUP', 'ORDER', 'LIMIT', 'OFFSET'))) continue;
    
                if (is_array($value)) {
                    $ops = array('>'=>1, '<'=>1, '>='=>1, '<='=>1, '!='=>1, 'IN'=>1, 'NOT IN'=>1, 'LIKE'=>1, 'BETWEEN'=>1, 'FIND_IN_SET'=>1);
                    foreach ($value as $op => $val) {
                        $op = strtoupper($op);
                        if (isset($ops[$op])) {
                            if (is_array($val)) {
                                $val = array_map(array($this->db, 'escape'), $val);
                                if ($op == 'BETWEEN') {
                                    $wheres[] = $column . ' BETWEEN ' . implode(' AND ', $val);
                                } else {
                                    $wheres[] = $column . ' ' . $op . ' (' . implode(',', $val) . ')';
                                }
                            } else {
                                if ($op == 'FIND_IN_SET') {
                                    $wheres[] = "FIND_IN_SET($val, $column)";
                                } else {
                                    $wheres[] = $column . ' ' . $op . ' ' . $this->db->escape($val);
                                }
                            }
                        }
                    }
                } else {
                    $wheres[] = $column . ' = ' . $this->db->escape($value);
                }
            }
    
            if (!empty($wheres)) {
                $where_clause .= ' WHERE ' . implode(' AND ', $wheres);
            }
            if (isset($where['GROUP'])) $where_clause .= ' GROUP BY ' . $where['GROUP'];
            if (isset($where['ORDER'])) $where_clause .= ' ORDER BY ' . $where['ORDER'];
            if (isset($where['LIMIT'])) $where_clause .= ' LIMIT ' . $where['LIMIT'];
            if (isset($where['OFFSET'])) $where_clause .= ' OFFSET ' . $where['OFFSET'];
        } else {
            $where_clause = $where;
        }
        return $where_clause;
    }
}
